# -*- coding: utf-8 -*-
import pendulum
from airflow.exceptions import AirflowSkipException
from datetime import timedelta
from time import time
from utils.operators.rich_sql_sensor import RichSqlSensor

cst = pendulum.timezone('Asia/Shanghai')
class BranchRichSqlSensor(RichSqlSensor):

    def pre_execute(self, context):
        day = cst.convert(context['ti'].execution_date) + timedelta(days=1)

        schedule_date = ['01', '15']

        if day.strftime('%d') not in schedule_date:
            print(f'{day.strftime("%d")} not in {schedule_date}, should skip')
            super().pre_execute(context)
            raise AirflowSkipException()
        else:
            print(f'{day.strftime("%d")} in {schedule_date}, run now')
            super().pre_execute(context)


label = f"dm_spmi_enter_port_weight_range_rate_month{int(time())}"
timeout = timedelta(hours=1).seconds
doris_spmi_dm__dm_spmi_enter_port_weight_range_rate_month = BranchRichSqlSensor(
    task_id='doris_spmi_dm__dm_spmi_enter_port_weight_range_rate_month',
    pool='broker_load_pool',
    email=['matthew.xiong@jtexpress.com', 'yl_bigdata@yl-scm.com'],
    task_concurrency=1,
    conn_id='new_doris',
    pre_sql=f"""
    TRUNCATE TABLE spmi_dm.dm_spmi_enter_port_weight_range_rate_month PARTITION (
         p{{{{ execution_date | date_add(1) | add_month(-1) | cst_month_nodash }}}}
    );
    LOAD LABEL spmi_dm.{label} (
        DATA INFILE(
          "hdfs://{{{{ var.value.hadoop_namespace }}}}/dw/hive/spmi_dm.db/external/dm_spmi_enter_port_weight_range_rate_month/mt={{{{ execution_date | date_add(1) | add_month(-1) | cst_month_dash }}}}/*"
          )   
        INTO TABLE dm_spmi_enter_port_weight_range_rate_month
        FORMAT AS 'PARQUET'(                               
                id
                ,entry_mark_mth              
                ,piece_financial_center_id  
                ,piece_financial_center_code
                ,piece_financial_center_name
                ,receiver_province_id       
                ,receiver_province_name     
                ,destination_id             
                ,destination_name           
                ,sum_type                   
                ,all_weight_range_cnt       
                ,all_weight_range_rate      
                ,weight_range1_cnt          
                ,weight_range1_rate         
                ,weight_range2_cnt          
                ,weight_range2_rate         
                ,weight_range3_cnt          
                ,weight_range3_rate         
                ,weight_range4_cnt          
                ,weight_range4_rate                           
        )
        columns from path as (mt)
        set(
                id                              =     id
                ,entry_mark_mth                 =    entry_mark_mth              
                ,piece_financial_center_id      =    piece_financial_center_id  
                ,piece_financial_center_code    =    piece_financial_center_code
                ,piece_financial_center_name    =    piece_financial_center_name
                ,receiver_province_id           =    receiver_province_id       
                ,receiver_province_name         =    receiver_province_name     
                ,destination_id                 =    destination_id             
                ,destination_name               =    destination_name           
                ,sum_type                       =    sum_type                   
                ,all_weight_range_cnt           =    all_weight_range_cnt       
                ,all_weight_range_rate          =    all_weight_range_rate      
                ,weight_range1_cnt              =    weight_range1_cnt          
                ,weight_range1_rate             =    weight_range1_rate         
                ,weight_range2_cnt              =    weight_range2_cnt          
                ,weight_range2_rate             =    weight_range2_rate         
                ,weight_range3_cnt              =    weight_range3_cnt          
                ,weight_range3_rate             =    weight_range3_rate         
                ,weight_range4_cnt              =    weight_range4_cnt          
                ,weight_range4_rate             =    weight_range4_rate         
        )
    )
    WITH BROKER '{{{{ var.json.doris_brokers | random_choice }}}}'
    PROPERTIES ('timeout'='{timeout}', 'max_filter_ratio'='0.0')
    """,
    poke_sql=f"SHOW LOAD FROM spmi_dm WHERE label = '{label}' ORDER BY CreateTime DESC LIMIT 1",
    sql_on_kill=f"CANCEL LOAD FROM spmi_dm WHERE LABEL = '{label}'",
    success=lambda r: r[2] == 'FINISHED',
    failure=lambda r: (r[2] is not None and r[2] == 'CANCELLED', str(r[7])),
    poke_interval=60,
    execution_timeout=timedelta(seconds=timeout + 120), )

doris_spmi_dm__dm_spmi_enter_port_weight_range_rate_month
